package main

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"log"
	"math"
)

/*
转化成二进制格式与原本数据转字符串相比会更节省空间
此包实现了对数据与byte之间的转换，以及varint的编解码
数据的byte序列化转换
type ByteOrder：可以定义自己的字节序结构，用于序列化和反序列化数据。
*/

func main() {
	var pi float64
	b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}
	buf := bytes.NewBuffer(b)
	err := binary.Read(buf, binary.LittleEndian, &pi)
	if err != nil {
		log.Fatalln("binary.Read failed:", err)
	}
	fmt.Println(pi)

	buf1 := new(bytes.Buffer)
	pi1 := math.Pi

	err1 := binary.Write(buf1, binary.LittleEndian, pi1)
	if err != nil {
		log.Fatalln(err1)
	}
	fmt.Println(buf.Bytes())

}

/*
参数列表: buf  需要解码的缓冲区
返回值:
1) int64 解码的数据
2) int  解析的字节数
功能说明:
Varint是从buf中解码并返回一个int64的数据,及解码的字节数(>0).如果出错,则返回数据0和一个小于等于0的字节数n,其意义为:
1) n == 0: buf太小
2) n < 0: 数据太大,超出64位,且-n为已解析字节数
*/

func Test1() {
	var sbuf []byte
	var buf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 16, 0, 1, 1}
	var bbuf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 192, 192, 1, 1}

	num, ret := binary.Varint(sbuf)
	fmt.Println(num, ret) //0 0

	num, ret = binary.Varint(buf)
	fmt.Println(num, ret) //580990878187261960 9

	num, ret = binary.Varint(bbuf)
	fmt.Println(num, ret) //0 -11
}

func Test2() {
	var sbuf []byte
	var buf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 16, 0, 1, 1}
	var bbuf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 192, 192, 1, 1}

	num, err := binary.ReadUvarint(bytes.NewBuffer(sbuf))
	fmt.Println(num, err) //0 EOF

	num, err = binary.ReadUvarint(bytes.NewBuffer(buf))
	fmt.Println(num, err) //1161981756374523920 <nil>

	num, err = binary.ReadUvarint(bytes.NewBuffer(bbuf))
	fmt.Println(num, err) //4620746270195064848 binary: varint overflows a 64-bit integer
}

/*

 */
func Test3() {
	var sbuf []byte
	var buf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 16, 0, 1, 1}
	var bbuf []byte = []byte{144, 192, 192, 129, 132, 136, 140, 144, 192, 192, 1, 1}

	num, err := binary.ReadVarint(bytes.NewBuffer(sbuf))
	fmt.Println(num, err) //0 EOF

	num, err = binary.ReadVarint(bytes.NewBuffer(buf))
	fmt.Println(num, err) //580990878187261960 <nil>

	num, err = binary.ReadVarint(bytes.NewBuffer(bbuf))
	fmt.Println(num, err) //2310373135097532424 binary: varint overflows a 64-bit integer
}

type Reader interface {
	Read(p string) (n int, err error)
}

func hhh() {
	var Reader Reader
	Reader.Read = haha
}

func haha(a string) (int, error) {
	return 1, errors.New("hihihi")
}
